import React, {useRef, useState} from 'react';
import {Card, message, PageHeader} from 'antd';

import moment from 'moment';
import {editGoods, findByBackId, findByfindBySelectList, findByGoodsAngent,} from '@/services/ant-design-pro/goods';
import {getResult} from '@/services/ant-design-pro/attribute';
import {useMount} from 'ahooks';
import MyUpload from '@/components/MyUpload';


import {useLocation} from 'umi';
import ProForm, {ProFormDateTimePicker, ProFormInstance, ProFormSwitch} from "@ant-design/pro-form";
import {
  ProFormDatePicker,
  ProFormDependency,
  ProFormDigit,
  ProFormItem,
  ProFormList,
  ProFormMoney,
  ProFormSelect,
  ProFormText
} from '@ant-design/pro-form/lib/components';
import './editor.less'
import BraftEditor, {EditorState} from "braft-editor";


const initValue = {
  name: '',
  imageId: 0,
  isIntegral: 0
};

const getAttr1 = async () => {
  return await getResult ( 'sys_global_state', 1 );
};
const addGoods: React.FC = () => {
  // @ts-ignore
  const [agents, setAgents] = useState<API.goodsAgentPrice[]> ();

  const [imageId, setImageId] = useState<number> ();
  const [imageIds, setImageIds] = useState<number[]> ();
  const [videoId, setVideoId] = useState<number> ();
  // @ts-ignore
  const [content, setContent] = useState<string> ("");
  // @ts-ignore
  const [editorState, setEditorState] = useState<EditorState> ();
  const handleChange = (editorState: { toHTML: () => any }) => {
    let html = editorState.toHTML ();
    console.log ( html )

   setContent ( html );
  };
  // @ts-ignore
  const [goods, setGoods] = useState<API.Goods> ( initValue );

  // @ts-ignore
  const {query} = useLocation ();

  const formRef = useRef<ProFormInstance<API.Goods>> ();
  useMount ( () => {
    console.log ( 'paramsparamsparams', location );
    //getAttr2 ().then ( r  =>console.log )
    findByBackId ( query?.id ).then ( (res: API.BaseDataResult<API.Goods>) => {
      setGoods ( res.data );

    //  setEditorState ( ContentUtils.insertHTML ( editorState, res?.data?.content ) );
setContent ( res?.data?.content?res?.data?.content:"" );
      formRef.current?.setFieldsValue ( res?.data );
    } );
    findByGoodsAngent ( query?.id ).then ( (value) => {
      formRef.current?.setFieldsValue ( {agents: value.data} );
    } );
  } );
//test
  const validateMessages = {
    required: '${label}不能为空！',
    types: {
      email: '${label} is not a valid email!',
      number: '${label} is not a valid number!',
    },
  };
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  return (
    <div>
      <Card
        title={
          <PageHeader
            className="site-page-header"
            onBack={() => window.history.back ()}
            title={query.id > 0 ? '编辑商品' : '添加商品'}
            subTitle={goods?.name}
          />
        }
        bordered={false}
      >
        <ProForm<API.Goods>
          validateMessages={validateMessages}
          initialValues={goods}
          onFinish={async (values) => {
            values = Object.assign ( values, {
              imageId: imageId,
              imageIds: imageIds,
              videoId: videoId,
            content: content,
            } );
            console.log ( values );
            let fieldsValue = formRef.current?.getFieldsValue ();
            console.log ( fieldsValue );
            // const val1 = await formRef.current?.validateFields();
            //  console.log('validateFields:', val1);
            // const val2 = await formRef.current?.validateFieldsReturnFormatValue?.();
            // console.log('validateFieldsReturnFormatValue:', val2);
            editGoods ( values )
              .then ( () => {
                message.success ( '提交成功' );
             //   window.history.back ();
              } )
              .catch ( (e) => {
                message.error ( '提交失败' );
              } );
          }}
          formRef={formRef}
          params={{id: '100'}}
          formKey="base-form-use-demo"
          autoFocusFirstInput
          onValuesChange={(e) => {
            console.log ( 'onValuesChange', e )
          }}

        >


          <ProForm.Group>


            <ProFormText hidden={true} width="md" name="id"/>
            <ProFormText
              help={'Bu bolda  sinaq  mazmun'}
              rules={[{required: true}]}
              width="md"
              name="name"
              label="商品名称"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
            <ProFormText
              rules={[{required: true}]}
              width="md"
              name="nameUg"
              label="维语名称"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormSwitch label="分配积分" name="isIntegral" width="md"/>
            <ProFormText
              width="md"
              name="integral"
              label="积分"
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormDatePicker
              label="发布时间"
              width="md"
              name="publishTime"
              initialValue={moment ( '2021-08-09' )}
            />
            <ProFormText
              rules={[{required: true}]}
              width="md"
              name="goodNumber"
              label="商品编号"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText
              rules={[{required: true}]}
              width="md"
              name="size"
              label="大箱装箱量"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
            <ProFormDigit
              width="md"
              name="name"
              label="中箱装箱量"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormSelect
              rules={[{required: true}]}
              debounceTime={300}
              request={async () => {
                return await findByfindBySelectList ();
              }}
              width="md"
              name="categoryId"
              label="商品分类"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
            <ProFormSelect

              debounceTime={300}
              request={async () => {
                return await getAttr1 ();
              }}
              rules={[{required: true}]}
              width="md"
              name="permit"
              label="是否计入业绩"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText
              rules={[{required: true}]}
              width="md"
              name="measure"
              label="计量单位"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
            <ProFormText
              rules={[{required: true}]}
              width="md"
              name="weight"
              label="单位重量"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText
              rules={[{required: true}]}
              width="md"
              name="inventory"
              label="云仓库存"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
            {/*<ProFormText  width="md" name="name" label="产品销量" tooltip="最长为 24 位" placeholder="请输入名称" />*/}
            <ProFormText
              rules={[{required: true}]}
              width="md"
              name="quantity"
              label="库存数量"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormMoney
              rules={[{required: true}]}
              width="md"
              name="marketPrice"
              label="市场价"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
            <ProFormMoney
              rules={[{required: true}]}
              width="md"
              name="retailPrice"
              label="零售价"
              tooltip="最长为 24 位"
              placeholder="请输入名称"
            />
          </ProForm.Group>

          <ProForm.Group >

            <ProFormSwitch label="活动设置" name="isActivty" />
          </ProForm.Group>
          <ProForm.Group  >

            <ProFormDependency name={['isActivty']}  >

              {({isActivty}) => {

                console.log ( isActivty )
                if (isActivty) {
                  return (<><ProFormDateTimePicker label={"开始时间"} name={"startActiveDate"} />
                    <ProFormDateTimePicker label={"结束时间"} name={"endActiveDate"} /></>)
                }
              }}
            </ProFormDependency>

          </ProForm.Group>
          <ProFormList

            creatorButtonProps={false}
            deleteIconProps={false}
            copyIconProps={false}
            name="agents"
            label="组件列表"
          >
            <ProForm.Group size={4}>
              <ProFormText
                disabled={true}
                width="sm"
                name="name"
                label="市场价"
                tooltip="最长为 24 位"
                placeholder="请输入名称"
              />
              <ProFormMoney
                rules={[
                  {
                    required: true,
                  },
                ]}
                width="sm"
                name="price"
                label="市场价"
                tooltip="最长为 24 位"
                placeholder="请输入名称"
              />
              <ProFormMoney
                rules={[
                  {
                    required: true,
                  },
                ]}
                width="sm"
                name="newPrice"
                label="零售价"
                tooltip="最长为 24 位"
                placeholder="请输入名称"
              />
              <ProFormMoney
                rules={[
                  {
                    required: true,
                  },
                ]}
                width="sm"
                name="activePrice"
                label="活动价"
                tooltip="最长为 24 位"
                placeholder="请输入活动价"
              />
              <ProFormDependency name={['isActivty']}  >

                {({isActivty}) => {

                  console.log ( isActivty )
                  if (isActivty) {
                    return (<><ProFormDateTimePicker label={"开始时间"} name={"startActiveDate"} />
                      <ProFormDateTimePicker label={"结束时间"} name={"endActiveDate"} /></>)
                  }
                }}
              </ProFormDependency>
            </ProForm.Group>
          </ProFormList>
          <ProForm.Group>
            <ProFormItem
              name="imageId"

              label="图片"
            >
              <MyUpload
                type={1}
                onChange={(event) => {
                  //  console.log(event?.id)
                  // @ts-ignore
                  setImageId ( event );
                  // @ts-ignore
                  formRef.current?.setFieldsValue ( {imageId: event} );
                }}
              ></MyUpload>
            </ProFormItem>
            <ProFormItem label="视频">
              <MyUpload
                type={2}
                onChange={(event) => {
                  //  console.log(event?.id)
                  // @ts-ignore
                  setVideoId ( event );
                  formRef.current?.setFieldsValue ( {imageId: event} );
                }}
              ></MyUpload>
            </ProFormItem>
          </ProForm.Group>
          <ProForm.Group>
            <ProFormItem

              name="images"
              label="多图片"
            >
              <MyUpload
                multis={true}
                type={1}
                onChange={(event) => {
                  console.log ( event )

                  // @ts-ignore
                  setImageIds ( event );
                  // @ts-ignore
                  formRef.current?.setFieldsValue ( {imageIds: event} );
                }}
              ></MyUpload>
            </ProFormItem>
          </ProForm.Group>
          <div className="editor-wrapper">
   {/*       <MyEditor content={goods?.content} onChange={(content1=> {
            console.log ( content1 )
         //   formRef.current?.setFieldValue("content", content1);
            setContent ( content1 );editor.less

          })}/>*/}
            <BraftEditor   value={BraftEditor.createEditorState(content)} onChange={handleChange}/>
          </div>
        </ProForm>
      </Card>
    </div>
  );
};
export default addGoods;
